<template>
  <el-card class="styles-conterner" :body-style="{ height: 'calc(100% - 100px)' }">
    <template #header>
      <div class="style-query" :style="{ height: '90px' }">
        <div class="style-query-title">
          <span class="normal-title">样式</span><span class="title-description">样式管理</span>
        </div>
        <el-form
          class="style-query-form"
          :model="styleQueryFormData"
          :inline="true"
        >
          <el-form-item label="工作空间名称 :">
            <el-select
              v-model="styleQueryFormData.workspace"
              clearable
              filterable
              placeholder="请选择工作空间"
            >
              <el-option
                v-for="workspaceItem in workspaceList"
                :key="workspaceItem.name"
                :label="workspaceItem.name"
                :value="workspaceItem.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="样式名称 :">
            <el-input v-model="styleQueryFormData.name" placeholder="请输入..." />
          </el-form-item>
          <el-form-item style="margin-left: auto">
            <el-button @click="reset">重置</el-button>
            <el-button @click="startQuery(true)">查询</el-button>
            <el-button type="primary" size="small" @click="addStyle">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <div class="card-body-conterner">
      <el-table
        :data="paginatedTableData"
        style="width: 100%"
        class="styles-table"
        header-cell-class-name="style-table-header-cell"
      >
        <el-table-column label="名称">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div>名称: {{ scope.row.name }}</div>
              </template>
              <template #reference>
                <el-tag>{{ scope.row.name }}</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="workspace" label="工作空间">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.workspace?.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="format" label="格式"> </el-table-column>
        <el-table-column prop="version" label="版本" width="100">
          <template #default="scope"> {{ scope.row.languageVersion?.version }} </template>
        </el-table-column>
        <el-table-column label="操作" width="130">
          <template #default="scope">
            <div class="operation-button-area">
              <span class="operation-button" title="编辑" @click="handleEdit(scope.row)">
                <img src="@/assets/images/edit.png" />
              </span>
              <span
                class="operation-button"
                title="删除"
                @click="handleDelete(scope.$index, scope.row)"
              >
                <img src="@/assets/images/delete.png" />
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="totalOrignTableData > 10"
        v-model:current-page="styleQueryFormData.pageNum"
        v-model:page-size="styleQueryFormData.pageSize"
        class="styles-pagination"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, total, sizes"
        :total="totalOrignTableData"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <addOrUpdate
            v-if="addOrUpdateDialogVisible"
            v-model:visible="addOrUpdateDialogVisible"
            :type="addOrUpdateDialogType"
            :styleInfo="currentStyle"
            @update-styles="startQuery(true)"
        ></addOrUpdate>
  </el-card>
</template>

<script setup lang="ts" name="authButton">
import { ElMessage, ElMessageBox } from 'element-plus'
import useWorkspaceModal from '@/composables/useWorkspace'
import useStylesModal from '@/composables/useStyles'
import { restHelperInstance } from '@/composables/useGeoHelper'
import addOrUpdate from './addOrUpdate.vue'
import { computed, onBeforeMount, onMounted, reactive, ref } from 'vue'
import type { IStyle } from 'geoserver-helper/interface'

const workspaceModal = useWorkspaceModal()
// 样式hook
const stylesModal = useStylesModal()
// 数据总数
const totalOrignTableData = ref(0)
// 当前选中的样式
let currentStyle: IStyle.StyleDetailInfo | undefined = undefined
// 工作空间列表
const workspaceList = workspaceModal.workspaceList

// 过滤状态（是否显示过滤条件）
const filterState = ref(false)
// 默认查询条件
const defaultStyleQueryFormData = {
  workspace: '',
  name: '',
  pageNum: 1,
  pageSize: 10,
}
// 查询表单
const styleQueryFormData = ref<any>(JSON.parse(JSON.stringify(defaultStyleQueryFormData)))
// 新增或编辑弹窗显隐
const addOrUpdateDialogVisible = ref(false)
// 新增或编辑类型
const addOrUpdateDialogType = ref<'新增' | '编辑'>('新增')
const orignTableData = ref<IStyle.StyleInfoOfList[]>([])
//分页数据
const paginatedTableData = computed<IStyle.StyleDetailInfo[]>(() => {
  return orignTableData.value
    .slice(
      (styleQueryFormData.value.pageNum - 1) * styleQueryFormData.value.pageSize,
      styleQueryFormData.value.pageNum * styleQueryFormData.value.pageSize,
    )
    .map((mapItem) => {
      const tempData = reactive<IStyle.StyleDetailInfo>({
        name: mapItem.name,
        format: '',
        languageVersion: {
          version: '',
        },
        workspace: undefined,
        filename: '',
        dateCreated: '',
        dateModified: '',
      })
      let workspaceName = ''
      if(mapItem.href.includes("workspaces")){
        const matchWorkspace = mapItem.href.match(/workspaces\/([^\/]+)\/styles/)
        if(matchWorkspace && matchWorkspace[1]){
          workspaceName = matchWorkspace[1]
        }
      }
      restHelperInstance
        .getStyleInfoApi(mapItem.name, workspaceName)
        .then((res) => {
          if (res && res.style) {
            tempData.name = res.style.name
            tempData.format = res.style.format
            tempData.languageVersion = res.style.languageVersion
            tempData.workspace = res.style.workspace
            tempData.filename = res.style.filename
            tempData.dateCreated = res.style.dateCreated
            tempData.dateModified = res.style.dateModified
          }
        })
      return tempData
    })
})
/**
 * @description: 样式查询
 */
const startQuery = (refresh: boolean = false) => {
  totalOrignTableData.value = 0
  orignTableData.value = []
  stylesModal.getStyleListAll(refresh, styleQueryFormData.value.workspace).then((res) => {
    if (res) {
      res.forEach((eachItem) => {
        if (
          !styleQueryFormData.value.name ||
          String(eachItem.name).includes(styleQueryFormData.value.name)
        ) {
          totalOrignTableData.value += 1
          orignTableData.value.push(eachItem)
        }
      })
    }
  })
}

/**
 * @description: 重置
 * @return {*}
 */
const reset = () => {
  styleQueryFormData.value = {
    ...JSON.parse(JSON.stringify(defaultStyleQueryFormData)),
  }
}

/**
 * @description: 页数改变事件
 * @param {number} val
 * @return {*}
 */
const handleSizeChange = () => {
  startQuery()
}
/**
 * @description: 当前页改变事件
 * @param {number} val 当前页
 * @return {*}
 */
const handleCurrentChange = () => {
  startQuery()
}

/**
 * @description: 新增样式
 * @return {*}
 */
const addStyle = () => {
  addOrUpdateDialogType.value = '新增'
  addOrUpdateDialogVisible.value = true
}
/**
 * @description: 编辑样式handler
 * @param { Styles.ResStyleInfo } row 待编辑样式
 */
const handleEdit = (row: IStyle.StyleDetailInfo) => {
  currentStyle = row
  addOrUpdateDialogType.value = '编辑'
  addOrUpdateDialogVisible.value = true
}

/**
 * @description: 删除样式handler
 * @param { Styles.ResStyleInfo } row 待删除样式
 */
const handleDelete = (index: number, row: IStyle.StyleInfoOfList) => {
  ElMessageBox.confirm(`确认删除${row.name}么?`, '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      restHelperInstance.deleteStyleApi(row.name, '').then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        startQuery(true)
      })
    })
    .catch(() => {})
}
onBeforeMount(() => {
  // 此处执行一次后确保 workspaceList 有值
  workspaceModal.getWorkspaceList()
})
onMounted(() => {
  startQuery()
})
</script>

<style scoped lang="scss">
@import './index';
</style>
